package com.shigui.news.dao.impl;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projection;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.shigui.news.dao.BaseDao;
import com.shigui.news.dao.CategoryDao;
import com.shigui.news.model.Category;
import com.shigui.news.model.User;
@Repository("categoryDao")
public class CategoryDaoImpl extends BaseDao implements CategoryDao {
	@Autowired
	private SessionFactory sessionFactory;
	


	@Override
	public Category selectById(Integer cateId) {
		
		Query query = getSession().createQuery("from Category where cateId=:cateId");
		
		query.setInteger("cateId", cateId);
		
		Category category = (Category)query.uniqueResult();
		
		return category;
	}

	@Override
	public List<Category> select(String sql, Integer page, Integer count) {

		Integer firstResult = (page-1) * count;
		
		Query query = getSession().createQuery(sql);
		
		List<Category> categories = query.list();
		
		return categories;
		
	}
	@Transactional
	@Override
	public void insert(Category category) {
		
		
		getSession().save(category);
	}
	@Transactional
	@Override
	public void update(Category category) {

		getSession().update(category);
		
	}
	@Transactional
	@Override
	public void delete(Category category) {
		
//		getSession().evict(category);
		getSession().delete(category);
//		getSession().clear();
	}

	@Override
	public Category select(Integer cateId, User user, String sql) {
		
		Query query = getSession().createQuery(sql);
		query.setInteger("cateId", cateId);
		
		return (Category) query.uniqueResult();
	}
	/**
	 * 此方法已废
	 */
	@Override
	public Integer countCategoryList(List<Category> categories) {
		
		Integer tatol=0;
		for(Category category : categories){
		
			Criteria criteria = getSession().createCriteria(Category.class)
				.add(Restrictions.eq("cateId", category.getCateId()))
				.setProjection(Projections.rowCount());
		
		tatol = Integer.valueOf(criteria.uniqueResult().toString());
		}
		return tatol;
		
	}

	@Override
	public List<Category> select() {
		
		Query query = getSession().createQuery("from Category");
		
		List<Category> categories = query.list();
		
		return categories;
		
	}
	

}
